package com.aizhixin.lab.docker.service;


import com.aizhixin.lab.common.utils.PageJdbcUtil;
import com.aizhixin.lab.config.Config;
import com.aizhixin.lab.course.template.domain.TemplateDomain;
import com.aizhixin.lab.docker.domain.FormData;
import com.aizhixin.lab.docker.domain.Image;
import com.aizhixin.lab.docker.entity.ImageInfo;
import com.aizhixin.lab.docker.repository.ImageInfoRepository;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

@Slf4j
@Service
@Transactional
public class DockerImageService {
    @Autowired
    private Config config;
    @Autowired
    private ImageInfoRepository imageInfoRepository;
    @Autowired
    private PageJdbcUtil pageJdbcUtil;

    RowMapper<Image> rm1 = new RowMapper<Image>() {

        @Override
        public Image mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            // TODO Auto-generated method stub
            Image domain = new Image();
//            domain.setIDrs.getString(1));
            domain.setName(rs.getString(2));
            domain.setDesc(rs.getString(3));
//            domain.setVmNum(rs.getInt(4));
            return domain;
        }
    };
    public List<Image> imageInfoList(String name){
        String sql="SELECT * FROM image_info WHERE image_name LIKE '%"+name+"%' OR image_desc like '%"+name+"%'";
        return pageJdbcUtil.getInfo(sql,rm1);
    }




    /**
     * 获取镜像列表
     * @param token
     * @param creator
     * @return
     */
    public  FormData<ArrayList<Image>> getImageList(String token, String creator,Long createBy) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("token", token);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(null, headers);
        String queryPath = config.getDockerHost() + "/v1/images/list";
        queryPath+="?creator=me";
        ResponseEntity<String> responseEntity = restTemplate.exchange(queryPath, HttpMethod.GET, request, String.class);
        FormData formData = JSON.parseObject(responseEntity.getBody(), FormData.class);
        ArrayList<Image> images = JSON.parseObject(formData.getData().toString(), new TypeReference<ArrayList<Image>>() {
        });
        List<ImageInfo> all = imageInfoRepository.findAll();
        List<ImageInfo> infos=new ArrayList<>();
        ArrayList<Image> imageArrayList=new ArrayList<>();
        for (Image image:images) {
            Boolean isExistImage=false;
            for (ImageInfo i:all) {
                if (image.getName().equals(i.getImagesName())){
                    image.setDesc(i.getImageDesc());
                    image.setExpire(i.getExpire());
                    image.setOverSold(i.getOverSold());
                    image.setSpec(i.getSpec());
                    image.setNum(i.getVmNum());
                    image.setIsDelete(i.getCreateBy().equals(createBy));
                    isExistImage=true;
                    break;
                }
            }
//            if (isExistImage){
//                ImageInfo info = new ImageInfo();
//                info.setId(UUID.randomUUID().toString());
//                info.setImagesName(image.getName());
//                info.setImageDesc(image.getDesc());
//                info.setVmNum(image.getNum());
//                info.setOverSold(image.getOverSold());
//                info.setSpec(image.getSpec());
//                info.setExpire(image.getExpire());
//                info.setCreatedDate(image.getCreated_at());
//                imageInfoRepository.save(info);
//            }
        if (!isExistImage){
            ImageInfo info = new ImageInfo();
            info.setImagesName(image.getName());
            info.setImageDesc(image.getDesc());
            info.setCreateBy(4L);
            imageInfoRepository.save(info);
        }
            imageArrayList.add(image);
        }
        formData.setData(imageArrayList);
        return formData;
    }

    /**
     * 获取指定镜像
     *
     * @param token
     * @param type
     * @param key
     * @return
     */
    public FormData getAppointImage(String token, Integer type, String key) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("token", token);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(null, headers);
        String queryPath = config.getDockerHost() + "/v1/images/get";
        if (!StringUtils.isEmpty(key)) {
            queryPath+="?key="+key+"&type="+type;
        }
        ResponseEntity<String> responseEntity = restTemplate.exchange(queryPath, HttpMethod.GET, request, String.class);
        JSONObject jsonObject = new JSONObject();
        FormData formData = JSON.parseObject(responseEntity.getBody(), FormData.class);
        ArrayList<Image> images = JSON.parseObject(formData.getData().toString(), new TypeReference<ArrayList<Image>>() {
        });
        List<ImageInfo> all = imageInfoRepository.findAll();
        ArrayList<Image> imageArrayList=new ArrayList<>();
        for (Image image:images) {
            for (ImageInfo i:all) {
                if (image.getName().equals(i.getImagesName())){
                    image.setDesc(i.getImageDesc());

                    break;
                }
            }
            if (StringUtils.isEmpty(image.getDesc())){
                image.setDesc("这是"+image.getName()+"的描述");
            }
            imageArrayList.add(image);
        }
        formData.setData(imageArrayList);
        return formData;
    }

    /**
     * 更新镜像
     *
     * @param token
     * @param name
     * @param desc
     * @return
     */
    public FormData editImage(String token, String name, String desc) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("token", token);
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.isEmpty(name)) {
            map.put("name", name);
        }
        if (!StringUtils.isEmpty(desc)) {
            map.put("desc", desc);
        }
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(map, headers);
        String queryPath = config.getDockerHost() + "/v1/images/update";
        ResponseEntity<String> responseEntity = restTemplate.exchange(queryPath, HttpMethod.PUT, request, String.class);
        JSONObject jsonObject = new JSONObject();
        FormData formData = JSON.parseObject(responseEntity.getBody(), FormData.class);
        return formData;
    }

    /**
     * 删除镜像
     * @param token
     * @param name
     * @return
     */
    public FormData deleteImage(String token, String name) {

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("token", token);
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.isEmpty(name)) {
            map.put("name", name);
        }
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(map, headers);
        String queryPath = config.getDockerHost() + "/v1/images/delete";
        ResponseEntity<String> responseEntity = restTemplate.exchange(queryPath, HttpMethod.DELETE, request, String.class);
        JSONObject jsonObject = new JSONObject();
        imageInfoRepository.deleteByImagesName(name);
        FormData formData = JSON.parseObject(responseEntity.getBody(), FormData.class);
        return formData;
    }

    public ImageInfo getImageInfo(String name){
        ImageInfo info = imageInfoRepository.findByImagesName(name);
        if (info==null){
            info=new ImageInfo();
            info.setVmNum(1);
            info.setImageDesc("describe image"+name);
            info.setImagesName(name);
            imageInfoRepository.save(info);
        }
        return info;
    }


}
